package com.ctrip.openapi.java.customed;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;
import org.xml.sax.InputSource;

import com.ctrip.openapi.java.base.DBPool;
import com.ctrip.openapi.java.base.DateUtil;
import com.ctrip.openapi.java.base.HttpAccessAdapter;
import com.ctrip.openapi.java.base.HttpRequestProperty;
import com.ctrip.openapi.java.base.SdkSystemException;
import com.ctrip.openapi.java.base.model.City;
import com.ctrip.openapi.java.base.model.Hotel;
import com.ctrip.openapi.java.base.model.HotelDesc;
import com.ctrip.openapi.java.base.model.Images;
import com.ctrip.openapi.java.base.model.PricePlan;
import com.ctrip.openapi.java.base.model.RelativePosition;
import com.ctrip.openapi.java.base.model.Room;
import com.ctrip.openapi.java.utils.ConfigData;
import com.ctrip.openapi.java.utils.SignatureUtils;

// Http������
public class HotelDescInfoAdapter {

	
	//==========================================================
	private static String createHotelDescriptionRequestXml(String hotelCode) {
		StringBuilder sb = new StringBuilder();
		try {
			sb.append("<Request><Header AllianceID=\"");
			sb.append(ConfigData.AllianceId);
			sb.append("\" SID=\"");
			sb.append(ConfigData.SId);
			sb.append("\" TimeStamp=\"");
			long timestamp = SignatureUtils.GetTimeStamp();
			sb.append(timestamp);
			sb.append("\" Signature=\"");

			String signature = SignatureUtils.CalculationSignature(timestamp
					+ "", ConfigData.AllianceId, ConfigData.SecretKey,
					ConfigData.SId, ConfigData.OTA_HotelDescriptiveInfo);
			sb.append(signature);
			sb.append("\" RequestType=\"");
			sb.append(ConfigData.OTA_HotelDescriptiveInfo);
			sb.append("\" /><HotelRequest>"
					+ "<RequestBody xmlns:ns=\"http://www.opentravel.org/OTA/2003/05\" "
					+ "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">"
					+ "<OTA_HotelDescriptiveInfoRQ  Version=\"1.0\" "
					+ "xsi:schemaLocation=\"http://www.opentravel.org/OTA/2003/05 OTA_HotelDescriptiveInfoRQ.xsd\" "
					+ "xmlns=\"http://www.opentravel.org/OTA/2003/05\" "
					+ "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
					+ "<HotelDescriptiveInfos>"
					+ "<HotelDescriptiveInfo HotelCode=\""
					+ hotelCode
					+ "\">"
					+ "<HotelInfo SendData=\"true\"/>"
					+ "<FacilityInfo SendGuestRooms=\"true\"/>"
					+ "<AreaInfo SendAttractions=\"true\" SendRecreations=\"true\"/>"
					+ "<ContactInfo SendData=\"true\"/>"
					+ "<MultimediaObjects SendData=\"true\"/>"
					+ "</HotelDescriptiveInfo>" + "</HotelDescriptiveInfos>"
					+ "</OTA_HotelDescriptiveInfoRQ>"
					+ "</RequestBody></HotelRequest></Request>");
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}

		return sb.toString();
	}

	/*private static String getFindHotelDescription(String hotelCode) {
		String request = getResponseFromCtrip(ConfigData.OTA_HotelDescriptiveInfo,createHotelDescriptionRequestXml(hotelCode));
		String url = "http://openapi.ctrip.com/Hotel/OTA_HotelDescriptiveInfo.asmx?wsdl";
		String paraName = "requestXML";
		HttpAccessAdapter httpAccessAdapter = new HttpAccessAdapter();
		String response = httpAccessAdapter.SendRequestToUrl(request, url,
				paraName);
		return response;
	}*/

	private static List<HotelDesc> findHotelDescs(String hotelCode){
		List<HotelDesc> hoteldescs=new ArrayList<HotelDesc>();
			String response=HttpAccessAdapter.getResponseFromCtrip(ConfigData.OTA_HotelDescriptiveInfo,createHotelDescriptionRequestXml(hotelCode));
			System.out.println(response);
	        StringReader read = new StringReader(response);
	        InputSource source = new InputSource(read);
	      
	        SAXBuilder builder = new SAXBuilder();
	        try {      
	        	 Document doc = builder.build(source);  
	        	 Element root = doc.getRootElement();
	        	 XPath xpath1 = XPath.newInstance("/Response/Header");
	        	 List list1 =xpath1.selectNodes(root);
	        	 Element item1 = (Element)list1.get(0);
	        	 System.out.println(item1.getAttributeValue("ResultCode"));
	        	    if("Fail".equals(item1.getAttributeValue("ResultCode"))){
	        		 System.out.println(item1.getAttributeValue("ResultMsg"));
	        	    }
	        	 
	        	 XPath xpath = XPath.newInstance("/Response/HotelResponse/*/*/*");
	             List list = xpath.selectNodes(root);
                 //Iterator iter = list.iterator();
	             //while (iter.hasNext()){
	             for(int i=0;i<list.size();i++){
	            	 HotelDesc hotelDesc=new HotelDesc();
	            	 Element hotelDescriptiveContent = (Element)list.get(i);
	            	 hotelDesc.setBrandCode(hotelDescriptiveContent.getAttributeValue("BrandCode"));
	            	 hotelDesc.setHotelCode(hotelDescriptiveContent.getAttributeValue("HotelCode")); 
	            	 hotelDesc.setHotelCityCode(hotelDescriptiveContent.getAttributeValue("HotelCityCode"));
	            	 
	            	 Element wb = (Element)hotelDescriptiveContent.getChildren().get(0);
	            	 hotelDesc.setBuild(wb.getAttributeValue("WhenBuilt")==null?"":wb.getAttributeValue("WhenBuilt"));
	            	 
	            	 XPath hotelDescriptiveInfoRS = XPath.newInstance("//ns:OTA_HotelDescriptiveInfoRS");
	            	 hotelDescriptiveInfoRS.addNamespace("ns", "http://www.opentravel.org/OTA/2003/05");
	            	 Element hdirs=(Element)hotelDescriptiveInfoRS.selectSingleNode(root);
	            	 
	            	 XPath segmentCategory = XPath.newInstance("//ns:SegmentCategory");
	            	 segmentCategory.addNamespace("ns", "http://www.opentravel.org/OTA/2003/05");
	            	 Element seg=(Element)segmentCategory.selectSingleNode(root);
	            	 if(seg!=null){
	            	 hotelDesc.setSegCategpry(seg.getAttributeValue("Code"));
	            	 }
	            	 else{
	            		 hotelDesc.setSegCategpry("");
	            	 }
	            	 XPath descriptiveText = XPath.newInstance("//ns:Service");
	            	 descriptiveText.addNamespace("ns", "http://www.opentravel.org/OTA/2003/05");
	            	 List<Element> desc=(List<Element>)descriptiveText.selectNodes(root);
	            	 
	            	 for(int j=0;j<desc.size();j++){
	            		 Element child=(Element)desc.get(j).getChildren().get(0);
	            		// System.out.println(desc.get(j).getAttributeValue("Code")+"--"+desc.get(j).getAttributeValue("ID")+"--"+child.getText());
	            		 if("1001".equals(desc.get(j).getAttributeValue("ID"))){
	            			 hotelDesc.setService1001((hotelDesc.getService1001()==null?"":(hotelDesc.getService1001()+"@"))+child.getText());
	            		 }else if("1002".equals(desc.get(j).getAttributeValue("ID"))){
	            			 hotelDesc.setService1002((hotelDesc.getService1002()==null?"":(hotelDesc.getService1002()+"@"))+child.getText());
	            		 }else if("1003".equals(desc.get(j).getAttributeValue("ID"))){
	            			 hotelDesc.setService1003((hotelDesc.getService1003()==null?"":(hotelDesc.getService1003()+"@"))+child.getText());
	            		 }else if("1004".equals(desc.get(j).getAttributeValue("ID"))){
	            			 hotelDesc.setService1004((hotelDesc.getService1004()==null?"":(hotelDesc.getService1004()+"@"))+child.getText());
	            		 }
	            	 }
	            	 
	            	 XPath guestRoom = XPath.newInstance("//ns:GuestRoom");
	            	 guestRoom.addNamespace("ns", "http://www.opentravel.org/OTA/2003/05");
	            	 List<Element> guestRooms=(List<Element>)guestRoom.selectNodes(root);
	            	 List<Room> roomlist=new ArrayList();
	            	 for(int k=0;k<guestRooms.size();k++){
	            		 Room room=new Room();
	            		 room.setRoomTypeName(guestRooms.get(k).getAttributeValue("RoomTypeName"));
	            		 
	            		 List<Element> children=guestRooms.get(k).getChildren();
	            		 room.setStandardOccupancy(children.get(0).getAttributeValue("StandardOccupancy"));
	            		 room.setSize(children.get(0).getAttributeValue("Size"));
	            		 room.setRoomTypeCode(children.get(0).getAttributeValue("RoomTypeCode"));
	            		 room.setFloor(children.get(0).getAttributeValue("Floor"));
	            		 room.setBedTypeCode(children.get(0).getAttributeValue("BedTypeCode"));
	            		 room.setQuantity(children.get(0).getAttributeValue("Quantity"));
	            		 
	            		 Element amenities=(Element)guestRooms.get(k).getChildren().get(1);
	            		 List<Element> amenity=amenities.getChildren();
	            		 for(int q=0;q<amenity.size();q++){
	            			 List<Element> cd=amenity.get(q).getChildren();
	            			
	            			 room.setAmenity((room.getAmenity()==null?"":(room.getAmenity()+"@"))+cd.get(0).getText());
	            		 }
	            		 room.setHotelCode(hotelCode);
	            		 roomlist.add(room);
	            		 
	            	 }
	            	 hotelDesc.setRooms(roomlist);
	            	 
	            	 XPath imageItem = XPath.newInstance("//ns:ImageItem");
	            	 imageItem.addNamespace("ns", "http://www.opentravel.org/OTA/2003/05");
	            	 List<Element> imageItems=(List<Element>)imageItem.selectNodes(root);
	            	 List<Images> imageList=new ArrayList();
	            	 
	            	 for(int im=0;im<imageItems.size();im++){
	            		 Images image=new Images();
	            		 image.setCategory(imageItems.get(im).getAttributeValue("Category"));
	            		 Element url=(Element)((Element)imageItems.get(im).getChildren().get(0)).getChildren().get(0);
	            		 image.setUrl(url.getText());
	            		 image.setHotelCode(hotelCode);
	            		 image.setCaption(((Element)imageItems.get(im).getChildren().get(1)).getAttributeValue("Caption"));
	            		 imageList.add(image);
	            	 }
	            	 hotelDesc.setImages(imageList);
	            	 
	            	 XPath description = XPath.newInstance("//ns:Description");
	            	 description.addNamespace("ns", "http://www.opentravel.org/OTA/2003/05");
	            	 List<Element> descriptions=(List<Element>)description.selectNodes(root);
	            	 for(int im=0;im<descriptions.size();im++){
	            		 if("5".equals(descriptions.get(im).getParentElement().getAttributeValue("Category"))){
	            			 hotelDesc.setDetailDesc(descriptions.get(im).getText());
	            		 }else if("11".equals(descriptions.get(im).getParentElement().getAttributeValue("Category"))){
	            			 hotelDesc.setDesc(descriptions.get(im).getText());
	            		 }
	            	 }
	            	 
	            	 /*System.out.println(hotelDesc.getBrandCode()+":"+hotelDesc.getHotelCode()
	            			 +":"+hotelDesc.getBuild()+":"+hotelDesc.getSegCategpry()+
	            			 ":"+hotelDesc.getRooms().get(1).getRoomTypeName()+
	            			 ":"+hotelDesc.getRooms().get(1).getAmenity()+
	            			 ":"+hotelDesc.getImages().get(0).getCaption()+
	            			 ":"+hotelDesc.getImages().get(0).getUrl()+":"+hotelDesc.getDetailDesc()+"-->"+hotelDesc.getDesc());*/
	            	 hoteldescs.add(hotelDesc);
	             }
	        }catch (JDOMException e) {    
        		e.printStackTrace(); 
        		} catch (IOException e) {  
        			e.printStackTrace(); 
        			}
        return hoteldescs;
	}

	private static void sychronizeHotelDescs(String hotelCode,Connection con) throws SQLException {
            //System.out.println(hotelCode);
			List<HotelDesc> hList = HotelDescInfoAdapter.findHotelDescs(hotelCode);
			int temp = 0;
			//Connection con = null;
			java.sql.PreparedStatement st = null;
			java.sql.PreparedStatement st1 = null;
			java.sql.PreparedStatement st2 = null;
			Map<String, String> paraMap = new HashMap<String, String>();
			//con = DBPool.getConnection();
			if (con != null)
				System.out.println("connection get....................ok");
			st = con.prepareStatement("insert into hoteldesc(hotelCode,brandCode,build,segcategoty,sdesc,detailDesc,service1001,service1002,service1003,service1004,hotelCityCode)"
					+ " values(?,?,?,?,?,?,?,?,?,?,?)");
			st1 = con
					.prepareStatement("insert into hotelroom (roomTypeName,standardOccupancy,size,roomTypeCode,floor,bedTypeCode,quantity,amenity,hotelCode,hotelCityCode)"
							+ " values(?,?,?,?,?,?,?,?,?,?)");
			st2 = con
					.prepareStatement("insert into images (hotelCode,category,url,caption,hotelCityCode)"
							+ " values(?,?,?,?,?)");
			
			Long beginTime = System.currentTimeMillis();
			con.setAutoCommit(false);

			for (int row = 0; row < hList.size(); row++) {
				st.setString(1, hList.get(row).getHotelCode());
				st.setString(2, hList.get(row).getBrandCode());// aa=aa+","+creator;
				st.setString(3, hList.get(row).getBuild()==null?"":hList.get(row).getBuild());
				st.setString(4, hList.get(row).getSegCategpry()==null?"":hList.get(row).getSegCategpry());
				st.setString(5, hList.get(row).getDesc()==null?"":hList.get(row).getDesc());
				st.setString(6, hList.get(row).getDetailDesc()==null?"":hList.get(row).getDetailDesc());
				st.setString(7, hList.get(row).getService1001()==null?"":hList.get(row).getService1001());
				st.setString(8, hList.get(row).getService1002()==null?"":hList.get(row).getService1002());
				st.setString(9, hList.get(row).getService1003()==null?"":hList.get(row).getService1003());
				st.setString(10,hList.get(row).getService1004()==null?"":hList.get(row).getService1004());
				st.setString(11,hList.get(row).getHotelCityCode()==null?"":hList.get(row).getHotelCityCode());
	/*System.out.println("hotelCode:"+hList.get(row).getHotelCode()+"  brandcode:"+hList.get(row).getBrandCode()+"  seg:"+hList.get(row).getSegCategpry()
			+"  desc:"+hList.get(row).getDesc()+"  detail:"+hList.get(row).getDetailDesc()+"  1001:"+hList.get(row).getService1001()
			+"  1002:"+hList.get(row).getService1002()+"  1003:"+hList.get(row).getService1003()+"  1004:"+hList.get(row).getService1004());	
		*/
				st.addBatch();
				
				//roomTypeName,standardOccupancy,size,roomTypeCode,floor,bedTypeCode,quantity,amenity,hotelCode
				for (int row1 = 0; row1 < hList.get(row).getRooms()
						.size(); row1++) {
					st1.setString(1, hList.get(row).getRooms().get(row1).getRoomTypeName());
					st1.setString(2, hList.get(row).getRooms().get(row1).getStandardOccupancy()==null?"":hList.get(row).getRooms().get(row1).getStandardOccupancy()
							);
					st1.setString(3, hList.get(row).getRooms().get(row1).getSize()==null?"":hList.get(row).getRooms().get(row1).getSize()
							);
					st1.setString(4, hList.get(row).getRooms().get(row1).getRoomTypeCode()
							);
					//System.out.println(hList.get(row).getRooms().get(row1).getRoomTypeName()+"==="+hList.get(row).getRooms().get(row1).getFloor()+"==="+hList.get(row).getRooms().get(row1).getHotelCode());
					st1.setString(5, hList.get(row).getRooms().get(row1).getFloor()==null?"999":hList.get(row).getRooms().get(row1).getFloor()
							);
					st1.setString(6, hList.get(row).getRooms().get(row1).getBedTypeCode()==null?"":hList.get(row).getRooms().get(row1).getBedTypeCode()
							);
					st1.setString(7, hList.get(row).getRooms().get(row1).getQuantity()==null?"":hList.get(row).getRooms().get(row1).getQuantity()
							);
					st1.setString(8, hList.get(row).getRooms().get(row1).getAmenity()==null?"":hList.get(row).getRooms().get(row1).getAmenity()
							);
					st1.setString(9, hList.get(row).getRooms().get(row1).getHotelCode()
							);
					st1.setString(10,hList.get(row).getHotelCityCode());
					st1.addBatch();
				
					
				}
				for (int row2 = 0; row2 < hList.get(row).getImages()
						.size(); row2++) {
					//hotelCode,category,url,caption
					st2.setString(1, hList.get(row).getImages().get(row2).getHotelCode());
					st2.setString(2, hList.get(row).getImages().get(row2).getCategory()
							);
					st2.setString(3, hList.get(row).getImages().get(row2).getUrl()
							);
					st2.setString(4, hList.get(row).getImages().get(row2).getCaption()
							);
					st2.setString(5,hList.get(row).getHotelCityCode());
					st2.addBatch();
				}
				/*
				 * if(row%1000==0){ st.executeBatch();st.clearBatch(); temp=0; }
				 * else { temp=row; }
				 */

			}
			/*
			 * if(temp!=0) {
			 */
			st2.executeBatch();
			st2.clearBatch();
			st1.executeBatch();
			st1.clearBatch();
			st.executeBatch();
			st.clearBatch();
			// }
			// System.out.println(aa+","+datestring);
			con.commit();
			Long endTime = System.currentTimeMillis();
			System.out.println("pst+batch：" + (endTime - beginTime) / 1000 + "秒");
			st2.close();
			st1.close();
			st.close();
			//con.close();

		}
	
	
	
	public static void downloadHotelDescriptiveInfo() throws SQLException, InterruptedException {
		Connection con = null;
		java.sql.Statement st = null;
		
		List<String> hotellist=new ArrayList<String>();
		con = DBPool.getConnection();
		
		//con.
		if (con != null)
			{
			st=con.createStatement();
			ResultSet rs=st.executeQuery("SELECT distinct hotelCode FROM hotel order by hotelCode+1 ");
			  
			while(rs.next()){
				hotellist.add(rs.getString("hotelCode"));
				//
			}
		}
		st.close();
		con.close();
	   
		for(int i=0;i<hotellist.size();i++){
			System.out.println("----------------start----------");
			if(new Integer(hotellist.get(i)).intValue()>=6455){
			HotelDescInfoAdapter.sychronizeHotelDescs(hotellist.get(i),DBPool.getConnection());
			System.out.println("----------------end-------"+hotellist.get(i)+"-----");
			
			System.out.println("");
			Thread.sleep(2000);
			}
		}
	}
	
  

	
	public static void main(String[] args) throws SQLException,
			InterruptedException, JDOMException, IOException, ParseException {
		    
		    HotelDescInfoAdapter.downloadHotelDescriptiveInfo();
		

	}

}
